<template>
  <a-modal
    v-model:visible="visible"
    title="AI扩图"
    id="image-out-painting"
    :footer="false"
    @cancel="closeModal"
  >
    <a-row :gutter="16">
      <a-col :span="12">
        <h4>原始图片</h4>
        <img :src="picture?.url" :alt="picture?.name" style="max-width: 100%" />
      </a-col>
      <a-col :span="12">
        <h4>扩图结果</h4>
        <img
          v-if="resultImageUrl"
          :src="resultImageUrl"
          :alt="picture?.name"
          style="max-width: 100%"
        />
      </a-col>
    </a-row>
    <div style="margin-bottom: 16px"></div>
    <a-flex>
      <a-button type="primary" @click="createTask" :loading="!!taskId" ghost>生成图片</a-button>
      <a-button v-if="resultImageUrl" type="primary"  @click="handleUpload" :loading="uploadLoading">应用结果</a-button>
    </a-flex>
  </a-modal>
</template>
<script setup lang="ts">
import { onUnmounted, ref } from 'vue'
import {
  createPictureOutPaintingTaskUsingPost, getPictureOutPaintingTaskUsingGet, uploadPictureByUrlUsingPost,
  uploadPictureUsingPost
} from '@/request/api/pictureController.ts'
import { message } from 'ant-design-vue'

interface Props {
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (picture: API.PictureVO) => void
}

const props = defineProps<Props>()
const visible = ref(false)
const resultImageUrl = ref<string | undefined>('')
const taskId = ref<string>()

const closeModal = () => {
  visible.value = false
}
const openModal = () => {
  visible.value = true
}
// 创建AI扩图任务
const createTask = async () => {
  if (!props.picture?.id) return
  const { data: res } = await createPictureOutPaintingTaskUsingPost({
    pictureId: props.picture.id,
    // 可根据需要设置扩图参数
    parameters: {
      xScale: 2,
      yScale: 2,
    },
  })
  if (res.code === 0 && res.data) {
    message.success('任务创建成功,请耐心等待...')
    console.log(res.data.output?.taskId)
    taskId.value = res.data.output?.taskId
    // 开启轮询
    startPolling()
  } else {
    message.error('任务创建失败' + res.message)
  }
}
// 定时器
let pollingTimer: NodeJS.Timeout = null
const startPolling = () => {
  if (!taskId.value) return;
  try {
    // 开启定时器，每隔3秒执行
    pollingTimer = setInterval(async () => {
      const { data:res } = await getPictureOutPaintingTaskUsingGet({ taskId: taskId.value })
      if (res.code === 0 && res.data) {
        const taskResult = res.data.output
        if (taskResult?.taskStatus=== 'SUCCEEDED') {
          message.success('扩图任务成功')
          resultImageUrl.value = taskResult.outputImageUrl
          // 清理定时器
          clearPolling()
        } else if (taskResult?.taskStatus === 'FAILED') {
          message.error('扩图任务失败')
          clearPolling()
        }
      }
    }, 3000)
  } catch (e) {
    console.error('轮询任务失败',e)
    message.error('轮询任务失败,请稍后重试')
    clearPolling()
  }

}
const clearPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value=null;
  }
}
// 卸载组件时，清理定时器,避免内存泄露
onUnmounted(()=> {
  clearPolling()
})
const uploadLoading = ref(false)
// 上传图片
const handleUpload = async () => {
  uploadLoading.value = true
  try {
    // 有图片就是修改，没有图片就是添加
    const params: API.uploadPictureUsingPOSTParams = props.picture ? { id: props.picture.id } : {}
    params.spaceId = props.spaceId
    if (resultImageUrl.value) {
      params.fileUrl = resultImageUrl.value
    }
    let { data: res } = await uploadPictureByUrlUsingPost(params)
    if (res.code === 0 && res.data) {
      // 上传成功
      message.success('上传成功')
      // 将信息返回给父组件
      props.onSuccess?.(res.data)
      closeModal()
    } else {
      // 上传失败
      message.error('上传失败' + res.message)
    }
  } catch (e) {
    // 上传失败
    message.error('上传失败' + e)
  } finally {
    uploadLoading.value = false
  }
}

defineExpose({
  openModal,
})
</script>
<style scoped lang="less">
#image-out-painting {
  text-align: center;
}
</style>
